package com.muyu.rabbitmq.config;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName:liuzezhang
 * @Description: 消息发送到 broker的确认  重写 confirm 方法
 * @Author: zhuwenqiang
 * @Date: 2023/10/23
 */
@Component
public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 当前类被初始化的时候执行的方法
     *
     */
    @PostConstruct
    public void init() {
        // 设置 rabbitTemplate 的消息发送到交换机确认
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 消息发送到交换机 无论成功或者失败 都会执行
     *
     * @param correlationData correlation data for the callback.
     * @param ack             true for ack, false for nack  true 成功  false 失败
     * @param cause           An optional cause, for nack, when available, otherwise null.
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("消息发送到broker成功！");
        } else {
            System.out.println("消息发送到broker失败，失败的原因是：" + cause);
        }
    }

}
